
package com.eworking.eim.user;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.RosterPacket;

import com.eworking.eim.util.EIMLog;

public class EIMRosterLinstener implements RosterListener {
    
    /** 日志输出标记 */
    private static final String _TAG = EIMRosterLinstener.class.getSimpleName();
    
    private EIMUserManager userManager = null;
    
    private Roster roster = null;
    
    public EIMRosterLinstener(EIMUserManager userManager, Roster roster) {
        this.userManager = userManager;
        this.roster = roster;
    }
    
    @Override
    public void entriesAdded(Collection<String> arg0) {
        
    }
    
    @Override
    public void entriesDeleted(Collection<String> arg0) {
        
    }
    
    @Override
    public void entriesUpdated(Collection<String> collJID) {
        // 所有好友账号集合
        List<String> lstRosterAccount = new ArrayList<String>();
        // 删除的好友账号集合
        List<String> delRosterAccount = new ArrayList<String>();
        for (String JID : collJID) {
            RosterEntry rosterEntry = this.roster.getEntry(JID);
            // 获取用户账号
            String account = EIMAccountUtils.getAccountFromJID(JID);
            // both双方已经是好友；from对方已经接受好友请求
            if (rosterEntry.getType() == RosterPacket.ItemType.both
                || rosterEntry.getType() == RosterPacket.ItemType.from) {
                lstRosterAccount.add(account);
            }
            if (rosterEntry.getType() == RosterPacket.ItemType.none) {
                if (this.userManager.getDeletedUserAccount().contains(JID)) {
                    delRosterAccount.add(account);
                } else {
                    // 拒绝用户
                    this.userManager.getUserListener().onUserRefused(account);
                }
                try {
                    this.roster.removeEntry(rosterEntry);
                } catch (XMPPException e) {
                    EIMLog.e(_TAG, "删除好友失败：" + e.getMessage());
                }
            }
            
            if (lstRosterAccount.size() > 0) {
                this.userManager.getUserListener().onUserAdded(lstRosterAccount);
            }
            if (delRosterAccount.size() > 0) {
                this.userManager.getUserListener().onUserDeleted(delRosterAccount);
            }
        }
    }
    
    @Override
    public void presenceChanged(Presence arg0) {
        
    }
}
